package com.wyc.timed;

import com.wyc.MethodCostTimeCount;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author
 */
public class PrintMethodCost {

    public static void print(){
        while (true){
            Map<String, SortedMap<Long, Long>> methodCount = MethodCostTimeCount.getMethodCount();
            long currentTimeMillis = System.currentTimeMillis();
            System.out.println("currentTimeMillis is : " + currentTimeMillis);
            long oneMinuteBefore = currentTimeMillis - 60000;
            for(Map.Entry<String, SortedMap<Long, Long>> entry : methodCount.entrySet()){

                //一分钟以前的数据进行移除
                System.out.println("remove before :" + entry.getValue().size());
                Iterator iterator = entry.getValue().entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<Long,Long> key = (Map.Entry<Long, Long>) iterator.next();
                    if(key.getKey() < oneMinuteBefore){
                        iterator.remove();
                    }
                }
                System.out.println("remove after :" + entry.getValue().size());

                //一分钟之内的请求方法和耗时记录
                SortedMap<Long, Long> oneMinuteMap = entry.getValue().subMap(oneMinuteBefore, currentTimeMillis);

                //按照value值进行升序排序
                List<Map.Entry<Long, Long>> list = new ArrayList<>(oneMinuteMap.entrySet());
                Collections.sort(list, Comparator.comparing(Map.Entry::getValue));

                int index90 = (int) (list.size() * 0.9);
                int index99 = (int) (list.size() * 0.99);
                Long tp90Time = list.get(index90).getKey();
                Long tp90Cost = list.get(index90).getValue();
                System.out.println(entry.getKey() + " TP90 is cost : " + tp90Cost + " ms, timestamp is : " + tp90Time);

                Long tp99Time = list.get(index99).getKey();
                Long tp99Cost = list.get(index99).getValue();
                System.out.println(entry.getKey() + " TP99 is cost : " + tp99Cost + " ms, timestamp is : " + tp99Time);
            }
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                System.out.println("Thread sleep exception!");
            }
            System.out.println("==============================");
        }
    }
}
